﻿using CommonClass;
using CompanyManagement.Models;
using Resources;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity.Validation;
using System.Data.OleDb;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace CompanyManagement.management
{
    public partial class Companies : System.Web.UI.Page
    {
        #region Properties

        CompanyDAO companyDao = new CompanyDAO();

        public List<Company> CompanyList { get; set; }

        #endregion

        public Companies()
        {
            CompanyList = new List<Company>();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            GridFilterMenuTranslate.TranslateGridFilterMenu(ref RadGrid1);
            GridFilterMenuTranslate.TranslateGridFilterMenu(ref RadGrid2);
            if (!IsPostBack)
            {
                if (Session["user"] == null || string.IsNullOrEmpty(Session["user"].ToString()))
                {
                    Response.Redirect("~/Login.aspx");
                }
                if (FileUpload1.HasFile)
                {
                    FileUpload1.Attributes.Clear();
                    FileUpload1 = new FileUpload();
                }
            }
        }

        void ClearMessage()
        {
            error.Visible = false;
            success.Visible = false;
            ltrError.Text = string.Empty;
            ltrSuccess.Text = string.Empty;
        }

        protected void linkbtImport_Click(object sender, EventArgs e)
        {
            ClearMessage();
            ImportExcel();
        }

        protected bool CheckExtention(FileUpload name)
        {
            string extentsion = Itech.Utils.CommonFunctions.getFileFormat(name.FileName);
            bool checkExtension = false;
            foreach (string strTempExtentsion in ConfigurationSettings.AppSettings["FILE_FORMAT_UPLOAD"].ToString().Split(".".ToCharArray()))
            {
                if (extentsion.ToLower() == strTempExtentsion.ToLower())
                {
                    checkExtension = true;
                    return true;
                }
            }
            if (name.FileBytes.Length < 1073741824)
            {
                checkExtension = true;
                return true;
            }
            if (checkExtension == false)
            {
                CommonClass.MessageBox.Show(GlobalResource_VN.ValidateFileUploadExtendsion);
                return false;
            }
            return false;
        }

        private void ImportExcel()
        {
            string file_name_thumbs = string.Empty;
            if (!string.IsNullOrEmpty(FileUpload1.FileName) && CheckExtention(FileUpload1) == true)
            {
                Sycomore.UploadFile Upload = new Sycomore.UploadFile();
                Upload.StrFileName = FileUpload1.FileName;
                Upload.StrFolder = Server.MapPath("~/importExcel/");
                Upload.Upload(FileUpload1);
                file_name_thumbs = "~/importExcel/" + Upload.StrFileName;
            }
            else
            {
                CommonClass.MessageBox.Show(GlobalResource_VN.ChoseExcelForImport);
                return;
            }
            string fullPath = Server.MapPath(string.Format(@"{0}", file_name_thumbs));

            DataTable dt = ImportByFileExcel(fullPath);
            // List company existed
            List<Company> companiesExisted = new List<Company>();
            //List<PinCard> pincodeSerials = new List<PinCard>();
            int index = -1;
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    index = dt.Rows.IndexOf(dr);
                    Company objCompany = AutoInsertOrUpdate(dr, index);
                    if (objCompany != null && objCompany.ID > 0)
                    {
                        companiesExisted.Add(objCompany);
                    }
                }
                catch (Exception ex)
                {
                    CommonClass.MessageBox.Show("Lỗi: " + ex.Message);
                }
            }
            if (companiesExisted.Count > 0)
            {
                RadGrid2.DataSource = companiesExisted;
                RadGrid2.DataBind();
                alertExisted.Visible = true;
                error.Visible = true;
                success.Visible = false;
                ltrError.Text = string.Format("Có {0} doanh nghiệp đã tồn tại trong hệ thống. Bạn vui lòng kiểm tra lại!", companiesExisted.Count);
            }
            else
            {
                error.Visible = false;
                success.Visible = true;
                ltrSuccess.Text = GlobalResource_VN.ImportExcelSuccessFull;
            }
            //RadGrid1.DataSource = CompanyList;
            RadGrid1.Rebind();
            // Clear file upload when finished
            FileUpload1.Attributes.Clear();
            FileUpload1 = new FileUpload();

        }

        private Company AutoInsertOrUpdate(DataRow dr, int index)
        {
            Company objCompany = new Company();
            Company objCompanyNew = new Company();
            try
            {
                if (string.IsNullOrEmpty(dr["Name"].ToString()))
                {
                    Tools.Logger(string.Format(GlobalResource_VN.CheckNullPincodeAndCost + "; Name:{0}", dr["Name"] == null ? "unkown" : dr["Name"].ToString()), "CompanyManagement", "AddCompany");
                    CommonClass.MessageBox.Show(string.Format(GlobalResource_VN.CheckNullPincodeAndCost));
                    return null;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("File Excel không đúng định dạng! Bạn vui lòng kiểm tra lại");
                return null;
            }

            CultureInfo provider = CultureInfo.InvariantCulture;
            try
            {
                objCompanyNew = new Company()
                {
                    CompanyNo = dr["CompanyNo"] == null ? "-1" : dr["CompanyNo"].ToString(),
                    Abbreviation = dr["Abbreviation"] == null ? "" : dr["Abbreviation"].ToString(),
                    Address = dr["Address"] == null ? "" : dr["Address"].ToString(),
                    BusinessReg = dr["BusinessReg"] == null ? "" : dr["BusinessReg"].ToString(),
                    Capital = dr["Capital"] == null ? "" : dr["Capital"].ToString(),
                    DirectorName = dr["DirectorName"] == null ? "" : dr["DirectorName"].ToString(),
                    DistrictCode = dr["DistrictCode"] == null ? "" : dr["DistrictCode"].ToString(),
                    MSN1 = dr["MSN1"] == null ? "" : dr["MSN1"].ToString(),
                    MSN2 = dr["MSN2"] == null ? "" : dr["MSN2"].ToString(),
                    MSN3 = dr["MSN3"] == null ? "" : dr["MSN3"].ToString(),
                    MSN4 = dr["MSN4"] == null ? "" : dr["MSN4"].ToString(),
                    Name = dr["Name"] == null ? "" : dr["Name"].ToString(),
                    Owner = dr["Owner"] == null ? "" : dr["Owner"].ToString(),
                    Phone = dr["Phone"] == null ? "" : dr["Phone"].ToString(),
                    Status = dr["Status"] == null || string.IsNullOrEmpty(dr["Status"].ToString()) ? 1 : Convert.ToInt32(dr["Status"].ToString()),
                    TaxCode = dr["TaxCode"] == null ? "" : dr["TaxCode"].ToString(),
                    TradingName = dr["TradingName"] == null ? "" : dr["TradingName"].ToString(),
                    WardCode = dr["WardCode"] == null ? "" : dr["WardCode"].ToString(),
                    ReasionDissolved = dr["ReasionDissolved"] == null ? "" : dr["ReasionDissolved"].ToString(),
                    CompanyTypeCode = dr["CompanyType"] == null ? "" : dr["CompanyType"].ToString(),
                    CompanyCreateDated = dr["CompanyCreateDated"] == null ? "" : ConvertDateTime(dr["CompanyCreateDated"]),
                    DissolvedDate = dr["DissolvedDate"] == null ? "" : dr["DissolvedDate"].ToString().Split('T').Last(),
                    IsActive = true
                };

                //if (companyDao.Insert(objCompanyNew) > 0)
                //{
                //    CompanyList.Add(objCompanyNew);
                //    //Tools.Logger(string.Format("Insert-ID:{0} - CompanyNo:{1} - Name: {2}", objCompanyNew.ID, dr["CompanyNo"].ToString(), dr["Name"].ToString()), "CompanyManagement", "AddCompany");
                //}
                if (!companyDao.CheckCompanyExisted(objCompanyNew))
                {
                    if (companyDao.Insert(objCompanyNew) > 0)
                    {
                        CompanyList.Add(objCompanyNew);
                    }
                }
                else
                {
                    Tools.Logger(string.Format("Existed-Index:{0} - CompanyNo:{1} - Name: {2}", index.ToString(), dr["CompanyNo"].ToString(), dr["Name"].ToString()), "CompanyManagement", "AddCompany");
                    objCompany = companyDao.GetCompanyByCompanyNo(objCompanyNew.CompanyNo);
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Tools.Logger(string.Format("Index:{2}-Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage, index), "CompanyManagement", "AddCompany");
                    }
                }
                objCompanyNew = null;
            }
            catch (Exception ex)
            {
                Tools.Logger(string.Format("Index:{0} - CompanyNo:{1} - Error:{2}", index.ToString(), dr["CompanyNo"].ToString(), ex.Message), "CompanyManagement", "AddCompany");
                objCompanyNew = null;
            }

            return objCompany;
        }

        private string ConvertDateTime(object createdDateDataRow)
        {
            try
            {
                string createDate = createdDateDataRow.ToString();
                if (createDate.Length > 10)
                {
                    return Convert.ToDateTime(createDate).ToString("dd/MM/yyyy");
                }
                else
                {
                    return createDate;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static DataTable ImportByFileExcel(string pathFile)
        {
            DataTable dtExcel = new DataTable();
            dtExcel.TableName = "CompanyTable";
            string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + pathFile + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
            //OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", pathFile));
            //  string SourceConstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + pathFile + "';Extended Properties= 'Excel 8.0'";
            OleDbConnection con = new OleDbConnection(SourceConstr);
            string query = "Select * from [Sheet1$]";
            OleDbDataAdapter data = new OleDbDataAdapter(query, con);
            data.Fill(dtExcel);
            con.Close();
            if (File.Exists(pathFile))
                File.Delete(pathFile);
            return dtExcel;
        }

        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = companyDao.GetCompanies();
        }

        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            ClearMessage();
            if (e.CommandName == RadGrid.FilterCommandName)
            {
                Pair laPaire = (Pair)e.CommandArgument;
                string a = RadGrid1.MasterTableView.FilterExpression;
                if (string.Compare((string)laPaire.Second, "Name") == 0)
                {
                    e.Canceled = true;

                    TextBox txtBox = (TextBox)((GridFilteringItem)e.Item)["Name"].Controls[0];
                    FiltreOriginalClient = txtBox.Text;

                    GridColumn colonneCachee = ((RadGrid)sender).MasterTableView.GetColumnSafe("NameFilter");
                    //colonneCachee.CurrentFilterFunction = (GridKnownFunction)(Enum.Parse(typeof(GridKnownFunction), Convert.ToString(laPaire.First, CultureInfo.InvariantCulture), true));
                    //colonneCachee.CurrentFilterValue = Tools.RemoveDiacritics(txtBox.Text);
                    //((RadGrid)sender).Rebind();

                    //string newFilter = "(it." + colonneCachee.UniqueName + " LIKE N\'%" + Tools.RemoveDiacritics(txtBox.Text) + "%\')";
                    string newFilter = string.Format("(iif(NameFilter == null, \"\", {0}).ToString().ToUpper().Contains(\"{1}\".ToUpper()))", colonneCachee.UniqueName, Tools.RemoveDiacritics(txtBox.Text));
                    RadGrid1.MasterTableView.FilterExpression = newFilter;
                    //GridFilteringItem filterItem = ((RadGrid)sender).MasterTableView.GetItems(GridItemType.FilteringItem)[0] as GridFilteringItem;
                    //filterItem.FireCommandEvent("Filter", new Pair((string)laPaire.First, "NameFilter"));
                    RadGrid1.Rebind();
                }
            }
            if (e.CommandName == Telerik.Web.UI.RadGrid.ExportToExcelCommandName)
            {
                ConfigureExport();
            }
        }

        void ConfigureExport()
        {
            RadGrid1.ExportSettings.ExportOnlyData = true;
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.OpenInNewWindow = false;
            RadGrid1.ExportSettings.FileName = "CompanyList";
        }

        protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.FilteringItem)
            {
                if (!string.IsNullOrEmpty(((TextBox)((GridFilteringItem)e.Item)["NameFilter"].Controls[0]).Text) && !string.IsNullOrEmpty(FiltreOriginalClient))
                {
                    ((TextBox)((GridFilteringItem)e.Item)["Name"].Controls[0]).Text = FiltreOriginalClient;
                }
            }
        }

        public string FiltreOriginalClient { get; set; }

        protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridFilteringItem)
            {
                GridFilteringItem filteringItem = e.Item as GridFilteringItem;
                (filteringItem["CompanyNo"].Controls[0] as TextBox).Width = Unit.Pixel(60);
                //(filteringItem["TaxCode"].Controls[0] as TextBox).Width = Unit.Pixel(60);
                //(filteringItem["BusinessReg"].Controls[0] as TextBox).Width = Unit.Pixel(60);
                (filteringItem["StrStatus"].Controls[1] as RadComboBox).Width = Unit.Pixel(120);
                (filteringItem["Address"].Controls[0] as TextBox).Width = Unit.Pixel(140);
            }
        }

        protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
        {
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            Company insertObj = new Company() { ID = -1, IsActive = true };


            insertObj.Name = (userControl.FindControl("txtName") as TextBox).Text;
            insertObj.TradingName = (userControl.FindControl("txtTradingName") as TextBox).Text;
            insertObj.Abbreviation = (userControl.FindControl("txtAbbreviation") as TextBox).Text;
            insertObj.DirectorName = (userControl.FindControl("txtDirectorName") as TextBox).Text;
            insertObj.Owner = (userControl.FindControl("txtOwner") as TextBox).Text;
            insertObj.Phone = (userControl.FindControl("txtPhone") as TextBox).Text;
            insertObj.Address = (userControl.FindControl("txtAddress") as TextBox).Text;
            insertObj.DistrictCode = (userControl.FindControl("txtDistrictCode") as TextBox).Text;
            insertObj.WardCode = (userControl.FindControl("txtWardCode") as TextBox).Text;
            insertObj.CompanyCreateDated = (userControl.FindControl("RadDateCompanyCreated") as RadDatePicker).SelectedDate.Value.ToString("dd/MM/yyyy");
            insertObj.CompanyNo = (userControl.FindControl("txtCompanyNo") as TextBox).Text;
            insertObj.BusinessReg = (userControl.FindControl("txtBusinessReg") as TextBox).Text;
            try
            {
                double.Parse((userControl.FindControl("txtCapital") as TextBox).Text);
                insertObj.Capital = (userControl.FindControl("txtCapital") as TextBox).Text;
            }
            catch (Exception)
            {
                Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Số vốn phải là ký tự số.";
                }
                e.Canceled = true;
                return;
            }
            insertObj.MSN1 = (userControl.FindControl("txtMSN1") as TextBox).Text;
            insertObj.MSN2 = (userControl.FindControl("txtMSN2") as TextBox).Text;
            insertObj.MSN3 = (userControl.FindControl("txtMSN3") as TextBox).Text;
            insertObj.MSN4 = (userControl.FindControl("txtMSN4") as TextBox).Text;
            insertObj.CompanyTypeCode = (userControl.FindControl("ddlCompanyType") as DropDownList).SelectedValue;
            insertObj.Status = Convert.ToInt32((userControl.FindControl("ddlStatus") as DropDownList).SelectedValue);
            //string month = (userControl.FindControl("ddlMonth") as DropDownList).SelectedValue;
            //string year = (userControl.FindControl("ddlYear") as DropDownList).SelectedValue;
            //newValues["DissolvedDate"] = string.Format("{0}/{1}", month,year);
            //newValues["ReasionDissolved"] = (userControl.FindControl("txtReasonDissolved") as TextBox).Text;

            try
            {
                if (companyDao.CheckCompanyExisted(insertObj))
                {
                    Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                    if (ltrMessage != null)
                    {
                        ltrMessage.ForeColor = Color.Red;
                        ltrMessage.Text = "Đã tồn tại doanh nghiệp này trong hệ thống. Vui lòng nhập tên doanh nghiệp hoặc CompanyNo khác.";
                    }
                    //error.Visible = true;
                    //success.Visible = false;
                    //ltrSuccess.Text = "Đã tồn tại doanh nghiệp này trong hệ thống.";
                    e.Canceled = true;
                    return;
                }
                if (companyDao.Insert(insertObj) > 0)
                {
                    error.Visible = false;
                    success.Visible = true;
                    ltrSuccess.Text = "Thêm mới doanh nghiệp thành công";
                    RadGrid1.MasterTableView.IsItemInserted = true;
                    RadGrid1.MasterTableView.Rebind();
                }
            }
            catch (Exception ex)
            {
                //Label lblError = new Label();
                //lblError.Text = "Unable to insert Employees. Reason: " + ex.Message;
                //lblError.ForeColor = System.Drawing.Color.Red;
                //RadGrid1.Controls.Add(lblError);
                //error.Visible = true;
                //success.Visible = false;
                //ltrSuccess.Text = "Có lỗi khi thêm mới doanh nghiệp. Vui lòng thử lại";
                Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Có lỗi khi thêm mới doanh nghiệp. Vui lòng thử lại.";
                }
                Tools.Logger("Error: " + ex.Message, "CompanyManagement", "InsertCommand");
                e.Canceled = true;
                return;
            }
        }

        protected void RadGrid1_EditCommand(object sender, GridCommandEventArgs e)
        {
        }

        protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            string companyID = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
            try
            {
                var deleteObj = new Company() { ID = Convert.ToInt32(companyID) };
                if (companyDao.Delete(deleteObj))
                {
                    error.Visible = false;
                    success.Visible = true;
                    ltrSuccess.Text = string.Format("Xóa doanh nghiệp thành công.");
                    RadGrid1.Rebind();
                }
            }
            catch (Exception ex)
            {
                error.Visible = true;
                success.Visible = false;
                Tools.Logger("Error: " + ex.Message, "CompanyManagement", "DeleteCommand");
                ltrError.Text = "Có lỗi khi xóa doanh nghiệp. Vui lòng thử lại";
            }
        }

        public List<StatusModel> GetStatus()
        {
            return new List<StatusModel>{
                new StatusModel{ Status= 1, StrStatus= "Đang hoạt động"},
                new StatusModel{ Status= 2, StrStatus= "Giải thể"},
                new StatusModel{ Status= 3, StrStatus= "Chuyển lĩnh vực"},
            };
        }

        protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
            GridEditableItem editedItem = e.Item as GridEditableItem;
            string companyID = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"].ToString();
            Company updateObj = companyDao.GetCompanyByID(Convert.ToInt32(companyID));
            if (updateObj == null)
            {
                Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Không tìm thấy doanh nghiệp trong hệ thống.";
                }
                e.Canceled = true;
                return;
            }
            updateObj.Name = (userControl.FindControl("txtName") as TextBox).Text;
            updateObj.TradingName = (userControl.FindControl("txtTradingName") as TextBox).Text;
            updateObj.Abbreviation = (userControl.FindControl("txtAbbreviation") as TextBox).Text;
            updateObj.DirectorName = (userControl.FindControl("txtDirectorName") as TextBox).Text;
            updateObj.Owner = (userControl.FindControl("txtOwner") as TextBox).Text;
            updateObj.Phone = (userControl.FindControl("txtPhone") as TextBox).Text;
            updateObj.Address = (userControl.FindControl("txtAddress") as TextBox).Text;
            updateObj.DistrictCode = (userControl.FindControl("txtDistrictCode") as TextBox).Text;
            updateObj.WardCode = (userControl.FindControl("txtWardCode") as TextBox).Text;
            updateObj.CompanyCreateDated = (userControl.FindControl("RadDateCompanyCreated") as RadDatePicker).SelectedDate.Value.ToString("dd/MM/yyyy");
            updateObj.CompanyNo = (userControl.FindControl("txtCompanyNo") as TextBox).Text;
            updateObj.BusinessReg = (userControl.FindControl("txtBusinessReg") as TextBox).Text;
            try
            {
                double.Parse((userControl.FindControl("txtCapital") as TextBox).Text);
                updateObj.Capital = (userControl.FindControl("txtCapital") as TextBox).Text;
            }
            catch (Exception)
            {
                Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Số vốn phải là ký tự số.";
                }
                e.Canceled = true;
                return;
            }
            updateObj.MSN1 = (userControl.FindControl("txtMSN1") as TextBox).Text;
            updateObj.MSN2 = (userControl.FindControl("txtMSN2") as TextBox).Text;
            updateObj.MSN3 = (userControl.FindControl("txtMSN3") as TextBox).Text;
            updateObj.MSN4 = (userControl.FindControl("txtMSN4") as TextBox).Text;
            updateObj.CompanyTypeCode = (userControl.FindControl("ddlCompanyType") as DropDownList).SelectedValue;
            updateObj.Status = Convert.ToInt32((userControl.FindControl("ddlStatus") as DropDownList).SelectedValue);

            string month = (userControl.FindControl("ddlMonth") as DropDownList).SelectedValue;
            string year = (userControl.FindControl("ddlYear") as DropDownList).SelectedValue;
            if (!month.Equals("-1") && !year.Equals("-1"))
            {
                updateObj.DissolvedDate = string.Format("{0}/{1}", month, year);
            }
            updateObj.ReasionDissolved = (userControl.FindControl("txtReasonDissolved") as TextBox).Text;

            try
            {
                if (companyDao.CheckCompanyExisted(updateObj))
                {
                    //error.Visible = true;
                    //success.Visible = false;
                    //ltrSuccess.Text = "Đã tồn tại doanh nghiệp này trong hệ thống.";
                    Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                    if (ltrMessage != null)
                    {
                        ltrMessage.ForeColor = Color.Red;
                        ltrMessage.Text = "Đã tồn tại doanh nghiệp này trong hệ thống. Vui lòng nhập tên doanh nghiệp hoặc CompanyNo khác.";
                    }
                    e.Canceled = true;
                    return;
                }
                if (companyDao.Update(updateObj))
                {
                    error.Visible = false;
                    success.Visible = true;
                    ltrSuccess.Text = "Cập nhật thông tin doanh nghiệp thành công";
                    RadGrid1.Rebind();
                }
            }
            catch (Exception ex)
            {
                //Label lblError = new Label();
                //lblError.Text = "Unable to insert Employees. Reason: " + ex.Message;
                //lblError.ForeColor = System.Drawing.Color.Red;
                //RadGrid1.Controls.Add(lblError);
                Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Có lỗi khi cập nhật thông tin doanh nghiệp. Vui lòng thử lại.";
                }
                //error.Visible = true;
                //success.Visible = false;
                Tools.Logger("Error: " + ex.Message, "CompanyManagement", "EditCommand");
                //ltrSuccess.Text = "Có lỗi khi cập nhật thông tin doanh nghiệp. Vui lòng thử lại";
                e.Canceled = true;
            }
        }

        protected void RadGrid1_ExcelMLWorkBookCreated(object sender, Telerik.Web.UI.GridExcelBuilder.GridExcelMLWorkBookCreatedEventArgs e)
        {
            e.WorkBook.Worksheets[0].Table.Columns[1].Hidden = true;
            e.WorkBook.Worksheets[0].Table.Columns[2].Hidden = true;
        }
    }

    public class StatusModel
    {
        public int Status { get; set; }
        public string StrStatus { get; set; }
    }
}